<!doctype html>
<html>
<head>
    <script type="text/javascript" src="lib/blockad.js"></script>
    <script type="text/javascript">
        if (Object.prototype.memberCount == undefined) { //在原型对象里面添加方法用于获取 调用对象的length
            Object.prototype.memberCount = function () {
                if (typeof(Object.keys) === "function") { //else用于兼容不支持 Object.keys 的浏览器
                    return Object.keys(this).length;
                } else {
                    var type = Object.prototype.toString.call(this);
                    if (type == '[object Array]') {
                        return this.length;
                    } else if (type === '[object Object]') {
                        var count = 0;
                        for (var i in this) {
                            if (this.hasOwnProperty(i)) {
                                count++;
                            }
                        }
                        return count;
                    } else {
                        return false;
                    }
                }
            }
        }

        if (Number.prototype.round == undefined) {
            Number.prototype.round = function (n) {
                return parseFloat(this.toFixed(n));
            }
        }
    </script>
    <meta charset="utf-8">
    <meta name="viewport" content="width=320, initial-scale=1, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <title>确认订单</title>
    <style type="text/css">
        * {
            box-sizing: border-box;
            font-family: "Heiti SC", "Hiragino Sans GB";
        }

        a {
            text-decoration: none;
            color: #555;
        }

        body {
            padding: 0;
            margin: 0;
            background-color: #F4F4F4;
            font-size: 14px;
            color: #444;
        }

        .visable {
            visibility: visible;
        }

        .unvisable {
            visibility: hidden;
        }

        .container {
            width: 100%;
            box-shadow: 0 1px 0 #E8E8E8;
            margin-bottom: 15px;
            position: relative;
            background-color: #FFF;
        }

        .one {
            border-bottom: 1px solid #E8E8E8;
            display: table;
            width: 100%;
            height: 100%;
            table-layout: fixed;
        }

        .one > div {
            display: table-cell;
        }

        .item-img {
            width: 100px;
            height: 100px;
            padding: 10px;
        }

        .item-img img {
            display: block;
            margin: auto;
            max-height: 80px;
            max-width: 80px;
        }

        .item-name, .item-price-count {
            height: 20px;
        }

        .price {
            color: red;
        }

        .price:before {
            color: red;
            content: "¥ ";
        }

        .count:after {
            content: " 件";
        }

        .item-sku {
            color: #999;
        }

        .item-price-count > div {
            display: table-cell;
            white-space: nowrap
        }

        .item-price {
            width: 1%;
        }

        .item-count {
            text-align: right;
            width: 1%;
        }

        .row {
            display: table;
            border-bottom: 1px solid #E8E8E8;
            width: 100%;
            table-layout: fixed;
        }

        .row > div {
            display: table-cell;
            vertical-align: middle;
            padding: 10px 10px;
        }

        .fixed {
            position: fixed;
            bottom: 0;
            height: 44px;
            background-color: #FFF;
            border-top: 1px solid #E8E8E8;
            width: 100%;
            display: table;
        }

        .btn {
            display: table-cell;
            vertical-align: middle;
            text-align: right;
            padding: 0 10px;
        }

        button[type=submit] {
            width: 110px;
            height: 30px;
            color: #FFF;
            background-color: #F02800;
            border: 1px solid #F02800;
            border-radius: 8px;
            font-size: 16px;
        }

        .right-text {
            text-align: right;
        }

        .title {
            font-weight: bold;
            width: 90px;
        }

        input[name=service], input[name=method] {
            display: none;
        }

        .check-border {
            display: inline-block;
            border-radius: 50%;
            width: 18px;
            height: 18px;
            border: 1px solid #F02800;
            position: relative;
        }

        .check-svg {
            transform: translate(-1px, -1px);
            -webkit-transform: translate(-1px, -1px);
            width: 18px;
            position: absolute;
            left: 0;
            top: 0;
        }

        .row label {
            vertical-align: 4px;
            color: #666;
        }

        #message {
            border: 1px solid #E8E8E8;
            -webkit-appearance: none;
            border-radius: 0;
            vertical-align: middle;
            width: 100%;
        }

        .result {
            width: 150px;
            height: auto;
            margin: 50px auto;
            font-size: 18px;
            color: #888;
        }

        .result img {
            width: 100px;
            opacity: 0.4;
        }

        .result div {
            text-align: center;
        }

        .warn {
            text-align: center;
            font-size: 20px;
        }

        .warn a {
            margin-top: 100px;
            color: #666;
            text-align: center;
            text-decoration: none;
        }

        .fastmail > div {
            line-height: 25px;
        }

        .fastmail .check-label {
            margin-left: 5px;
        }

        .btn > .message {
            color: red;
            width: calc(100% - 116px);
            text-align: center;
            font-size: 10px;
        }

        .btn > .message, .btn > button {
            display: inline-block;
        }
    </style>
</head>
<body>
<?php
require_once("app-component.php");
//{   obj 格式
//    "items": [{
//        "item_id": "2826",
//        "count": "7",
//            "sku_id": {
//                "fab": "1901",
//                  "size": "59"
//                  }
//    }]
//}

$json = json_decode(base64_decode($_GET["str"]), true);
$user_id = get_magic_quotes_gpc() ? $json["user_id"] : addslashes($json["user_id"]);

$user_token = get_magic_quotes_gpc() ? $json["user_token"]['token'] : addslashes($json["user_token"]['token']);
if (!verify($user_id, $user_token)) {
    echo "<div class='warn'><a href='webView://login'>请登录之后再购买</a></div>";
    return;
}
$obj = [];
$obj['items'] = $json["items"];

$crowd_price_id = $json["id"];

//测试
//$user_id = 2009;
//$post = '{"items": [{"item_id": "2826","count": "7"}]}';
//$crowd_price_id = 1;
//$user_token = '9c08a7ceeacf367b30a47208b8bd92a075141c';
//$obj = json_decode($post, true);
//http://test.jajahome.com/furniture/order_crowd.php?str=eyJpZCI6IjEiLCJpdGVtcyI6W3siY291bnQiOiIzIiwiaXRlbV9pZCI6IjI4MjYifV0sInVzZXJfaWQiOiIyMDYwIiwidXNlcl90b2tlbiI6eyJzaWQiOiI5NDMyNjQiLCJ0b2tlbiI6ImUyZGMxNDBiMWNlYzVkMmNjMTA0MTc0YjY2NTM5YTE3M2RiZjkzIn19

$ret = getPriceIdOrSku($crowd_price_id);


if (isset($ret["price_id"]) && !empty($ret["price_id"])) {
    $obj["items"][0]["price_id"] = $ret["price_id"];
} else {
    $obj["items"][0]["sku_id"] = $ret["sku_id"];
}

$crowd = getCrowd($crowd_price_id);
$postage = $crowd['postage'];
$crowd_price = $crowd['price'];

$obj["parse"] = parseItem($obj["items"], true);//obj 里面添加了单品信息
$obj["parse"][0]['crowd_price'] = $crowd_price;

$address = getAddress($user_id);

?>
<script type="text/javascript">
    var item_info = JSON.parse('<?= json_encode($obj["items"][0])?>');
    var detail_info = JSON.parse('<?= json_encode($obj["parse"])?>');
</script>
<style type="text/css">
    .address-icon, .item-img {
        vertical-align: middle;
    }

    .address-info, .item-info {
        vertical-align: top;
    }

    .address-icon {
        width: 50px;
    }

    .address-icon img {
        display: block;
        margin: auto;
    }

    .address-info, .item-info {
        padding: 10px 10px 10px 0;
    }

    .address-name-phone {
        margin-bottom: 5px;
    }

    .address-name-phone > div {
        display: table-cell;
    }

    .address-name {
        width: 70%;
        word-break: break-all;
        word-wrap: break-word;
    }

    .address-tel {
        text-align: right;
        width: 1%;
    }

    .address-detail {
        word-break: break-all;
        word-wrap: break-word;
    }

    .address-d {
        position: relative;
        background-color: #FFF;
        transform: translate3d(0, 0, 0);
        -webkit-transform: translate3d(0, 0, 0);
        backface-visibility: hidden;
        -webkit-backface-visibility: hidden;
    }

    .address-d.active {
        z-index: 99;
    }

    .show:not(.active) {
        animation-name: flodin;
        animation-duration: 0.25s;
        animation-timing-function: linear;
        animation-fill-mode: forwards;
        -webkit-animation-name: flodin;
        -webkit-animation-duration: 0.25s;
        -webkit-animation-timing-function: linear;
        -webkit-animation-fill-mode: forwards;
        display: block;
    }

    .hide:not(.active) {
        height: 0;
        display: none;
    }

    @keyframes flodin {
        0% {
            height: 0;
            opacity: 0;
        }
        100% {
            height: 89px;
            opacity: 1;
        }
    }

    .item-discount, .tz-discount {
        color: #AAA;
        display: inline-block;
    }

    .item-discount {
        margin-right: 10px;
    }

    .warn {
        padding: 5px;
        height: 40px;
        line-height: 28px;
        background-color: rgba(255, 0, 0, 0.1);
        border: 1px solid rgba(255, 0, 0, 0.4);
        color: #F00;
    }

    .warn a {
        color: #F00;
        text-decoration: none;
    }

    .discount, .lead_time {
        display: table-cell;
        color: #AAA;
    }

    .blank {
        height: 44px;
        width: 100%;
    }

    .install-method .check-border {
        vertical-align: top;
    }

    .install-method .check-label {
        margin-left: 5px;
        width: calc(100% - 25px);
        display: inline-block;
    }

    .check-label {
        color: #666;
    }

    .coupon-left {
        width: 120px;
        font-size: 0;
    }

    .coupon-left > div {
        display: table-cell;
    }

    .coupon-radio {
        vertical-align: middle;
    }

    .coupon-left img {
        max-width: 90px;
        max-height: 90px;
    }

    .clean_coupon {
        float: right;
        border: 1px solid #CCC;
    }
</style>
<div class="container address-container">
    <?php if (empty($address)): ?>
        <div class="warn">您还没有地址&nbsp;&nbsp;&nbsp;&nbsp;<a href="webView://address">去添加地址>></a></div>
    <?php else: ?>
    <?php
    $default_address = false;
    for ($i = count($address) - 1; $i >= 0; $i--) {
        if ($address[$i]["default"]) {
            $default_address = true;
        }
    }
    if (!$default_address) {
        $address[0]['default'] = 1;
    }
    ?>
    <?php for ($i = 0;
    $i < count($address);
    $i++): ?>
    <?php if ($address[$i]["default"]): ?>
    <div class="address-d active hide" data-id="<?= $address[$i]["id"] ?>">
        <div class="address-t one">
            <div class="address-icon">
                <img src="images/location-icon.png" width="36" class="visable">
            </div>
            <?php else: ?>
            <div class="address-d hide" data-id="<?= $address[$i]["id"] ?>">
                <div class="address-t one">
                    <div class="address-icon">
                        <img src="images/location-icon.png" width="36" class="unvisable">
                    </div>
                    <?php endif; ?>
                    <div class="address-info">
                        <div class="address-name-phone">
                            <div class="address-name"><?= $address[$i]["name"] ?></div>
                            <div class="address-tel"><?= $address[$i]["mobile"] ?></div>
                            <input type="hidden" name="address_id" value="<?= $address[$i]["id"] ?>">
                        </div>
                        <div class="address-detail">
                            <?= $address[$i]["city"] . "<br>" . $address[$i]["detail"] ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php endfor; ?>
            <?php endif; ?>
        </div>

        <div class="container item-container">
        </div>

        <div class="container orderinfo-container">
            <div class="row">
                <div class="title">结算</div>
            </div>
            <div class="row">
                <div class="title">服务</div>
                <div class="service">
                    <?php
                    switch ($postage) {
                        case 0:
                            $msg = "不包邮";
                            break;
                        case 1:
                            $msg = "包邮";
                            break;
                        case 2:
                            $msg = "至最近物流点";
                            break;
                        default:
                            $msg = "";
                    }
                    echo $msg;
                    ?>
                </div>
            </div>
            <div class="row">
                <div class="title">合计件数</div>
                <div class="count right-text" id="item_total_count"></div>
            </div>
            <div class="row">
                <div class="title">合计金额</div>
                <div class="price right-text" id="item_total_price">
                </div>
            </div>
            <div class="row">
                <div class="title">买家留言</div>
                <div class="right-text"><textarea id="message"></textarea></div>
            </div>
        </div>

        <div class="blank"></div>
        <div class="fixed">
            <div class="btn">
                <div class="message"></div>
                <button type="submit" onClick="checkAddress()">提交订单</button>
            </div>
        </div>
        <script type="text/javascript">
            var addressExpand = 0;//0:关闭状态，1:展开状态
            function bindAddress() {
                var address = document.querySelectorAll(".address-d");
                for (var i = 0; i < address.length; i++) {
                    address.item(i).addEventListener("click", function () {
                        var address = document.querySelectorAll(".address-d");
                        if (addressExpand == 0 && this.classList.contains("active")) {
                            for (var i = 0; i < address.length; i++) {
                                address.item(i).classList.remove("hide");
                                address.item(i).classList.add("show");
                            }
                            addressExpand = 1;
                        }
                        else if (addressExpand && this.classList.contains("active")) {
                            for (var i = 0; i < address.length; i++) {
                                address.item(i).classList.remove("show");
                                address.item(i).classList.add("hide");
                            }
                            addressExpand = 0;
                        }
                        else if (addressExpand && (!this.classList.contains("active"))) {
                            for (var i = 0; i < address.length; i++) {
                                address.item(i).classList.remove("show");
                                address.item(i).classList.remove("active");
                                address.item(i).classList.add("hide");
                            }
                            this.classList.add("active");
                            var tt = document.querySelector("img[class=visable]")
                            tt.classList.remove("visable");
                            tt.classList.add("unvisable");
                            this.querySelector("img").classList.remove("unvisable");
                            this.querySelector("img").classList.add("visable");
                            addressExpand = 0;
                        }
                    });
                }
            }

            window.onload = function () {
                bindAddress();
            };

            function checkAddress() {
                var address = document.querySelector('.address-d.active .address-detail').innerHTML;
                if (address.indexOf('<br>')) {
                    address = address.split('<br>')[0].replace(/(^\s*)|(\s*$)/g, "").split(' ');
                } else {
                    address = address.replace(/(^\s*)|(\s*$)/g, "").split(' ');
                }
                var last = address[address.length - 1];
                var fd = new FormData();
                fd.append('q', 'check-address');
                fd.append('address', last);
                fd.append("user_id", "<?= $user_id?>");
                fd.append("user_token", "<?= $user_token?>");
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var response = JSON.parse(xhr.responseText);
                        if (response['result'] == 1) {
                            submitOrder();
                        } else {
                            document.querySelector('.message').textContent = '请先升级到最新版本，更新您的收货地址。';
                        }
                    }
                };
                xhr.open('POST', 'calc.php', true);
                xhr.send(fd);
            }

            function submitOrder() {
                var userInfo = {};
                userInfo["message"] = document.getElementById("message").value;

                if (document.querySelector(".address-d.active") != null && document.querySelector(".address-d.active").dataset.id) {
                    userInfo["address_id"] = document.querySelector(".address-d.active").dataset.id;
                }
                else {
                    return;
                }

                var fd = new FormData();
                fd.append("q", "submitCrowd");
                fd.append("item_info", JSON.stringify(item_info));
                fd.append("user_info", JSON.stringify(userInfo));
                fd.append("user_id", <?= $user_id?>);
                fd.append("user_token", "<?= $user_token?>");
                fd.append("total_price", parseInt(item.total_price));
                fd.append("crowd_price_id", "<?= $crowd_price_id?>");
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            var response = JSON.parse(xhr.responseText);

                            if (response["state"]) {
                                var html = "<div class=\"result\"><div><img src=\"images/success.png\"></div><div>订单提交成功</div></div>";//订单提交成功
                                setTimeout(function () {
                                    location.href = 'webView://order?order_id=' + response['trade_no']
                                }, 1000);//跳转至付款页面
                            }
                            else {
                                var html = "<div class='result'><div><img src='images/failed.png'></div><div>"+response['error']+"<br><a href='webView://close'>重新选择</a></div></div>";
                            }
                            document.body.innerHTML = html;
                        }
                        else {
                            console.error(xhr.statusText);
                        }
                    }
                };
                xhr.open('POST', 'calc.php', true);
                xhr.send(fd);
            }

            var Item = function () {
                this.conatiner = document.querySelector('.item-container');
                this.itemObj = null;
                this.node = '';
                this.total_price = 0;
            };
            Item.prototype.create = function (obj) {
                var sku_name = {'mat': '材质', 'fab': '面料', 'size': '尺寸'};

                var sku_str = '';
                if (obj.sku != null) {
                    for (var i in obj.sku) {
                        if (obj.sku.hasOwnProperty(i)) {
                            if (i === 'size') {
                                continue;
                            } else {
                                sku_str += sku_name[i] + ':' + obj.sku[i];
                            }
                        }
                    }
                    if (typeof(obj.sku.size) != 'undefined') {
                        sku_str += (sku_str != '' ? '<br>' : '') + '尺寸:' + obj.sku.size;
                    }
                }

                this.node = document.createElement('div');
                this.node.classList.add('item');
                this.node.classList.add('one');
                this.node.innerHTML = '<div class="item-img">' +
                    '<img src="<?= $url . $path?>' + obj.img_url + '">' +
                    '</div>' +
                    '<div class="item-info">' +
                    '<div class="item-name">' + obj.name + '</div>' +
                    '<div class="item-price-count">' +
                    '<div class="item-price price">' + obj.crowd_price + '</div>' +
                    '<div class="item-count count">' + obj.count + '</div>' +
                    '</div>' +
                    '<div class="item-sku">' + sku_str + '</div>' +
                    '<div class="discount"></div>' +
                    '<div class="lead_time">' + (obj.lead_time ? '供货周期:' + obj.lead_time + ';' : '') + '</div>' +
                    '</div>';
                this.conatiner.appendChild(this.node);
            };

            Item.prototype.calc = function () {
                var item = this.itemObj[0];
                Object.prototype.toString.call(item.count) == '[object String]' ? item.count = parseInt(item.count) : '';
                Object.prototype.toString.call(item.crowd_price) == '[object String]' ? item.crowd_price = parseInt(item.crowd_price) : '';

                var total_count = item.count;
                this.total_price = item.crowd_price * item.count;
                var discount = '众筹优惠价';

                this.create(item);

                document.querySelector('#item_total_count').textContent = total_count;
                document.querySelector('#item_total_price').textContent = parseInt(this.total_price);
                document.querySelector('.discount').textContent = discount;
            };

            var item = new Item();
            item.itemObj = detail_info;
            item.calc();

        </script>
</body>
</html>